package com.ysw.spring.api_security.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.collect.Maps;
import org.apache.commons.collections.MapUtils;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName JwtUtil
 * @Description json wen token util
 * @Author ysw
 * @Date 2022/4/24 1:09
 */
public class JwtUtil {
    public static void main(String[] args) {
        HashMap<String, String> map = Maps.newHashMap();
        map.put("name","1");
        map.put("age","2");
        String token = JwtUtil.getToken(map);
        System.out.println(token);
        DecodedJWT tokenInfo = getTokenInfo(token);
        System.out.println(tokenInfo);
    }
    /**
     * 签名salt
     */
    private static String SIGN = "JWT_SIGN";

    /**
     * 获取token
     * @return
     */
    public static String getToken(Map<String,String> payloadMap){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);
        JWTCreator.Builder builder = JWT.create();
        payloadMap.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SIGN));
        return token;
    }

    /**
     * 获取token信息，抛异常的话验证失败
     * @param token
     * @return
     */
    public static DecodedJWT getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        return verify;
    }

    /**
     * 验证token的合法性
     * @param token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }


}